const id = sessionStorage.getItem('id');

// 自定义开始和结束时间
let startTime;
let endTime;
// 拼接日期和时间
let inputStartTimeString;
let inputStartTime;
let inputEndTimeString
let inputEndTime;
// 设置上限和下限
let maxLimit = 20;
const minLimit = 1;

// 界面加载获取商品信息，商品轮播图，商品秒杀信息
window.onload = function() {
    const nicknameElement = document.querySelector('#user');
    const nickname = sessionStorage.getItem('nickname');
    if (nickname) {
        nicknameElement.textContent = nickname;
    } else {
        nicknameElement.textContent = "登录|注册";
    }
    // 根据运行状态显示加载动画
    let ajaxCounter = 0;
    const totalAjaxCalls = 3; // 总共的 AJAX 请求数量

    function checkAllAjaxComplete() {
        ajaxCounter++;
        if (ajaxCounter === totalAjaxCalls) {
            document.getElementById('loading').style.display = 'none';
        }
    }

    // 获取商品信息
    $.ajax({
        url: "/goods",
        method: "get",
        data: {num: 2,id: id},
        dataType: "json",
        success: function(dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const goodsNameElement = document.getElementById('goods-name');
            goodsNameElement.textContent = data[0].name;
            sessionStorage.setItem("goodsName",data[0].name);
            const goodsPriceElement = document.getElementById('goods-price');
            goodsPriceElement.textContent = data[0].price;
            sessionStorage.setItem("original price",data[0].price);
            sessionStorage.setItem("current price",data[0].price);
            const goodsNumElement = document.getElementById('goods-residue');
            goodsNumElement.textContent = data[0].inventory;
            sessionStorage.setItem("residue",data[0].inventory);
            sessionStorage.setItem("goodsType","0");
            checkAllAjaxComplete();
        }
    })

    // 获取商品轮播图
    $.ajax({
        url: "/goods",
        method: "get",
        data: {num: 3,id: id},
        dataType: "text",
        success: function (dataString) {
            image = JSON.parse(dataString);
            const contentElement = document.querySelector('.small-box');
            for (let i=0; i<image.length; i++){
                contentElement.innerHTML += `<div class="img"><img src="`+ image[i] +`" alt="图片"></div>`
            }
            checkAllAjaxComplete();
        }
    })

    // 获取秒杀信息
    $.ajax({
        url: "/goods",
        method: "get",
        data: {num:7,id:id},
        dataType: "json",
        success: function (dataString) {
            if (dataString === "[]"){
                const timedown = document.getElementById("timedown");
                timedown.style = "display:none;";
                const priceTitle = document.getElementById("title");
                priceTitle.innerHTML = "<p style='margin-top: 70px; font-size: 20px; font-weight: bold;'>会员价：</p>"
                const info = document.getElementById("myMarquee");
                info.innerHTML= "当前商品不在秒杀活动范围，可会员价直接购买！"
                checkAllAjaxComplete();
                return;
            }
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            startTime=data[0].startTime + ":00";
            endTime=data[0].endTime + ":00";
            inputStartTimeString = year + "-" + (month >= 10 ? month : "0" + month) + "-" + (day >= 10 ? day : "0" + day) + " " + startTime;
            inputStartTime = +new Date(inputStartTimeString);
            inputEndTimeString = year + "-" + (month >= 10 ? month : "0" + month) + "-" + (day >= 10 ? day : "0" + day) + " " + endTime;
            inputEndTime = +new Date(inputEndTimeString);
            countDown();
            setInterval(countDown, 1000);
            const goodsPriceElement = document.getElementById('goods-price');
            goodsPriceElement.textContent = data[0].price;
            sessionStorage.setItem("current price",data[0].price);
            const goodsNumElement = document.getElementById('goods-residue');
            goodsNumElement.textContent = data[0].number;
            sessionStorage.setItem("residue",data[0].number);
            maxLimit = data[0].stock;
            sessionStorage.setItem("goodsType","1");
            checkAllAjaxComplete();
        }
    })
    document.getElementById('myMarquee').start();
    getComment();
}

// 获取按钮和输入框元素
const minusButton = document.querySelector('.minus');
const addButton = document.querySelector('.add');
const goodsNumInput = document.getElementById('goods-num');

// 减少按钮点击事件
minusButton.addEventListener('click', function() {
    let currentValue = parseInt(goodsNumInput.value);
    if (currentValue > minLimit) {
        goodsNumInput.value = currentValue - 1;
    }
});

// 增加按钮点击事件
addButton.addEventListener('click', function() {
    let currentValue = parseInt(goodsNumInput.value);
    if (currentValue < maxLimit) {
        goodsNumInput.value = currentValue + 1;
    }
});

// 输入框输入事件，确保输入值在范围内
goodsNumInput.addEventListener('input', function() {
    let currentValue = parseInt(goodsNumInput.value);
    if (isNaN(currentValue) || currentValue < minLimit) {
        goodsNumInput.value = minLimit;
    } else if (currentValue > maxLimit) {
        goodsNumInput.value = maxLimit;
    }
});

// 获取需要操作的元素
// 左边大图
let big_box=document.querySelector(".big-box");
// 图片集合
let imgs=document.getElementsByClassName("img");
// 定时器
let timer= null;
// 当前图片下标
let index= 0;
let image;

// 重置函数
function reset(){
    for(let i=0;i<imgs.length;i++){
        imgs[i].className="img";
    }
}
// 选中函数
function selected(){
    reset();
    imgs[index].className="img active";
}
// 轮播函数
function play(){
    timer=setInterval(function(){
        selected();
        big_box.style.backgroundImage="url(" + image[index] + ")";
        index++;
        if(index===5){
            index=0;
        }
    },1500);
}

// 循环绑定每个小图片的鼠标移动事件
setTimeout(function() {
    for(let i=0;i<imgs.length;i++){
        // 鼠标移动到小图片上时触发
        imgs[i].onmousemove=function(){
            // 左边大图变成当前的小图片
            big_box.style.backgroundImage="url(" + image[i] + ")";
            // 执行重置函数并关闭定时器
            reset();
            clearInterval(timer);
            // 更新当前图片下标并执行轮播
            index=i+1;
            if(index===5){
                index=0;
            }
            play();
        }
    }
}, 2000);

// 执行轮播
play();

const hour = document.querySelector(".hour");
const minute = document.querySelector(".minute");
const second = document.querySelector(".second");

// 获取当前日期
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1; // 月份从0开始，需要加1
const day = today.getDate();
const timedown = document.getElementById("timedown");
const text1 = document.getElementById("text1");
const text2 = document.getElementById("text2");
const toBuy = document.getElementById("toBuy");

// 未到时间信息
function disabled(){
    timedown.style = "background-color: grey;";
    text1.innerHTML = "即将开始<br>秒杀";
    text2.innerHTML = "距开始还有";
    toBuy.style = "background-color: grey;border: 1px solid grey";
    toBuy.onclick= "";
}

// 倒计时逻辑
function countDown() {
    const nowTime = +new Date();
    let times;
    if (nowTime < inputStartTime) {
        // 如果当前时间比开始时间早，则以开始时间作为倒计时
        times = (inputStartTime - nowTime) / 1000;
        disabled();
    } else if (nowTime >= inputStartTime && nowTime <= inputEndTime) {
        // 如果在开始时间和结束时间期间，则以结束时间作为倒计时
        times = (inputEndTime - nowTime) / 1000;
    } else {
        // 如果当前时间比开始和结束都迟，则跳到第二天进行倒计时
        inputStartTime = +new Date(inputStartTimeString) + 24 * 60 * 60 * 1000; // 加一天
        inputEndTime = +new Date(inputEndTimeString) + 24 * 60 * 60 * 1000; // 加一天
        times = (inputStartTime - nowTime) / 1000;
        disabled();
    }
    let h = parseInt(times / 60 / 60 % 24);
    h = h >= 10 ? h : "0" + h;
    hour.innerHTML = h;
    let m = parseInt(times / 60 % 60);
    m = m >= 10 ? m : "0" + m;
    minute.innerHTML = m;
    let s = parseInt(times % 60);
    s = s >= 10 ? s : "0" + s;
    second.innerHTML = s;
}

// 前往购买（登录判断）
function goToBuy(){
    const goodsId = sessionStorage.getItem("id");
    sessionStorage.setItem("goodImage","./images/goods/img_"+goodsId+".png");
    sessionStorage.setItem("amountType","2");
    sessionStorage.setItem("number",goodsNumInput.value)
    const nickname = sessionStorage.getItem("nickname");
    if (nickname === null){
        showInfo("未登录，请返回登录！");
        window.location.href = 'login.html';
    } else {
        window.location.href = 'verify.html';
    }
}

// 新增评论
function addComment(){
    const CommentNickname = document.getElementById("CommentNickname").value;
    const CommentContent = document.getElementById("CommentContent").value;
    if (CommentNickname === "" || CommentContent === ""){
        showInfo("请填写完整！");
    } else {
        $.ajax({
            url:"/comment",
            method: "get",
            data:{
                "type":"add",
                "goodsId": sessionStorage.getItem("id"),
                "nickname": CommentNickname,
                "content": CommentContent
            },
            success: function (data) {
                if (data === "success"){
                    showInfo("评论成功！");
                    document.getElementById("CommentNickname").value = "";
                    document.getElementById("CommentContent").value = "";
                    getComment();
                } else
                    showInfo("评论失败！");
            }
        })
    }
}

// 获取评论
function getComment() {
    $.ajax({
        url: "/comment",
        method: "get",
        data: {
            "type": "list",
            "goodsId": sessionStorage.getItem("id")
        },
        dataType:"json",
        success: function (dataString) {
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const commentList = document.getElementById("commentList");
            commentList.innerHTML = "";
            data.forEach(item => {
                const row = document.createElement('div');
                row.className = "comment";
                row.innerHTML = `
                    <div class="comment-header">
                        <img src="./images/avatar/780.jpg" alt="头像" class="comment-avatar">
                        <div class="comment-info">
                            <span class="comment-name">${item.nickName}</span>
                            <span class="comment-time">${item.time}</span>
                        </div>
                    </div>
                    <div class="comment-content">
                        ${item.content}
                    </div>
                `;
                commentList.appendChild(row);
            })
        }
    });
}